$(function (){
    // 初始化部分
    $('.controlContent input').css("background-color", '#e9ecef');
    $('.controlContent select').css("background-color", '#e9ecef');
    // 可见规则列表
    let visibleRuleList=[];

    // 价格规则列表
    let priceRuleList=[];
    // 请求用户级别，用户类型
    $(function (){
        $.ajax({
       timeout:30000,
            url: window.Http+ "/system/dict/data/getDictList",
            type: 'GET',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            data: {
                dictType: 'user_level'
            },
            success:function (res){
                if (res.code===200){
                    priceUserLevelCas.setOptions(dataFormat(res.data,'dictValue','dictLabel'))
                    visibleUserLevelCas.setOptions(dataFormat(res.data,'dictValue','dictLabel'))
                    res.data.forEach((item)=>{
                        userLevel[Number(item.dictValue)]=item.dictLabel;
                    })
                }
            }
        })
        $.ajax({
       timeout:30000,
            url:window.Http+ "/system/dict/data/getDictList",
            type: 'GET',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            data: {
                dictType:'user_type'
            },
            success:function (res){
                if (res.code===200){
                    priceUserTypeCas.setOptions(dataFormat(res.data,'dictValue','dictLabel'))
                    visibleUserTypeCas.setOptions(dataFormat(res.data,'dictValue','dictLabel'))
                    res.data.forEach((item)=>{
                        userType[item.dictValue]=item.dictLabel;
                    })
                }
            }
        })
        // 获取可见规则列表
        $.ajax({
       timeout:30000,
            url: window.Http + "/system/control/list/all",
            type: 'GET',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            success:function (res){
                if (res.code===200){
                    visibleRuleList=res.data;
                    // console.log('visibleRuleList', visibleRuleList)
                    visibleRuleTable.reload({data:res.data})
                }else {
                    layer.msg('获取可见规则失败')
                }
            }
        })
        // 获取价格规则列表
        $.ajax({
       timeout:30000,
            url: window.Http + "/system/buy/list",
            type: 'GET',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            success:function (res){
                if (res.code===200){
                    // priceRuleCas.setOptions(dataFormat(res.rows,"id","systemBuyName"))
                    priceRuleList=res.rows;
                    priceRuleTable.reload({data:res.rows})
                }else {
                    layer.msg('获取价格规则失败')
                }
            }
        })
    })
	//改变注册方式
	layui.form.on('radio(registerType)', function(data){
		if(data.value == 1){
		  $("#uploadRootFile").removeClass("disabledNone");
            $('input[type=text]').prop("disabled", true);
            $('input[type=text]').css("background-color", '#e9ecef');
            $('input[type=button]').prop("disabled", true);
            $('input[type=button]').css("background-color", '#e9ecef');
            $('textarea').prop("disabled", true);
            $('textarea').css("background-color", '#e9ecef');
            $('input[name=engineLoginCode]').prop("disabled", true);
            $('input[name=id]').prop("disabled", true);
            $('input[name=engineLoginCode]').css("background-color", '#e9ecef');
            $('input[name=id]').css("background-color", '#e9ecef');
		}else{
		  $("#uploadRootFile").addClass("disabledNone");
            $('input[type=text]').prop("disabled", false);
            $('input[type=text]').css("background-color", '#fff');
            $('input[type=button]').prop("disabled", false);
            $('input[type=button]').css("background-color", '#fff');
            $('textarea').prop("disabled", false);
            $('textarea').css("background-color", '#fff');
            $('input[name=engineLoginCode]').prop("disabled", true);
            $('input[name=id]').prop("disabled", true);
            $('input[name=engineLoginCode]').css("background-color", '#e9ecef');
            $('input[name=id]').css("background-color", '#e9ecef');
		}
	});
    // 获取URL中的查询参数部分
    const queryString = window.location.search;
    // 解析查询参数字符串，将其转换为对象
    const urlParams = new URLSearchParams(queryString);
    // 获取id参数的值
    const id = urlParams.get('id');
    // 选择的可见规则id
   let controlRuleId=-1;
    // 选择的价格规则id
   let buyRuleId=-1;
    // 如果id存在就进行表单赋值
    if (id){
        // 获取数据通道详情
        $.ajax({
       timeout:30000,
            url: window.Http + "/datasourceBase/"+id,
            type: 'GET',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            success: function (res) {
                if (res.code===200){
                  const database=res.data;
                  $('#rootEditOrAdd').html(`数据通道修改<p>Data Root Edit</p>`)
                    console.log('database', database)
                    form.val('BaseInfoForm',database)
                    // 规则赋值
                    const visibleRuleData=visibleRuleList?.find(item=>item.id===res.controlRuleId);
                    console.log('visibleRuleList', visibleRuleList)
                    console.log('visibleRuleData', visibleRuleData)
                    visibleFormValue(visibleRuleData)
                    const priceRuleData=priceRuleList?.find(item=>item.id===res.buyRuleId);
                    formValue(priceRuleData)
                    // 图标展示
                      $('#dataSourceIconUrl').attr("src",database.iconUrl)

                    // 人工注册数据通道 提交按钮
                    $('#submitAllForm').on('click',function (){
                        console.log('data', data)
                        const formdata=form.val('BaseInfoForm')
                        formdata.sourceNumber=Number(formdata.sourceNumber)
                        // const controlRuleId=visibleRuleCas.getCheckedValues()
                        // const buyRuleId=priceRuleCas.getCheckedValues()
                        delete formdata.verifyCode;
                        data=formdata;
                        data.controlRuleId=controlRuleId;
                        data.buyRuleId=buyRuleId
                        data.iconUrl=url
                        data.id=id;
                        data.status=2
                        $.ajax({
       timeout:30000,
                            url: window.Http + "/datasourceBase/update",
                            type: 'PUT',
                            headers: {
                                'Authorization': "Bearer " + sessionStorage.getItem('Token')
                            },
                            data:JSON.stringify(data),
                            contentType:"application/json",
                            success:function (res){
                                if (res.code===200){
                                    layer.msg('修改成功')
                                    // setTimeout(function(){
                                    //     window.location.href='../../mySpace.html'
                                    // },1000)
                                }else {
                                    layer.msg(res.msg)
                                }
                            }
                        })

                    })
                }else {
                    layer.msg(res.msg)
                }
            }
        })
    }else {
        $('#submitAllForm').on('click',function (){
            console.log('data', data)
            const formdata=form.val('BaseInfoForm')
            formdata.sourceNumber=Number(formdata.sourceNumber)
            // const buyRuleId=priceRuleCas.getCheckedValues()
            delete formdata.verifyCode;
            data=formdata;
            data.controlRuleId=controlRuleId;
            data.buyRuleId=buyRuleId
            data.iconUrl=url
            data.status=2
            if (data.id==''){
                delete data.id
            }
            $.ajax({
       timeout:30000,
                url: window.Http + "/datasourceBase",
                type: 'POST',
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                data:JSON.stringify(data),
                contentType:"application/json",
                success:function (res){
                    if (res.code===200){
                        layer.msg('注册成功')
                        //     setTimeout(function(){
                        //         window.location.href='../../mySpace.html'
                        //     },1000)
                    }else {
                        layer.msg(res.msg)
                    }
                }
            })

        })
    }
    const upload = layui.upload;
    const form = layui.form;
    const table=layui.table;
    // 用户类型，用户级别列表（用于展示，索引为value，值为label）
    let userType=[]
    let userLevel=[]
    // 表单注册提交数据
    let data;
    // 图标url
    let url;
	//显示或隐藏更多设置
	var setMoreState = false;
	$("#butnMoreSet").click(function(){
		if(setMoreState){
			$(this).text("更多设置");
			$(".MoreSet").addClass("disabledNone");
		}else{
			$(this).text("收起设置");
			$(".MoreSet").removeClass("disabledNone");
		}
		setMoreState = !setMoreState;
	})
    // 可见规则下拉框
    let visibleUserLevelCas=layui.layCascader(  {
        elem:`#visibleUserLevel`,
        clearable: true, // 显示清除按钮
        disabled:true,
        // options:data,
        props: {
            multiple: false, // 允许多选
            // strictMode:true//开启严格模式
        },
    })
    visibleUserLevelCas.changeEvent(function (value){
        console.log('级别的变化',value)
    })
    let visibleUserTypeCas=layui.layCascader({
        elem:`#visibleUserType`,
        clearable: true, // 显示清除按钮
        // options:data,
        disabled:true,
        props: {
            multiple: true, // 允许多选
            // strictMode:true//开启严格模式
        },
        // value:selectedData
    })
    visibleUserTypeCas.changeEvent(function (value,node){
        console.log('类型的变化：',value,node)
    })
    let visibleSpeUserCas=layui.layCascader({//单选
        elem:`#visibleSpeUser`,
        clearable: true, // 显示清除按钮
        disabled:true,
        props: {
            multiple: true, // 允许多选
            // strictMode:true//开启严格模式
        },
    })
    visibleSpeUserCas.changeEvent(function (value){
        console.log('用户变化',value,typeof value)
    })
    // 价格规则下拉框
    // 用户类型和用户级别，指定用户级联选择器对象
    let priceUserLevelCas=layui.layCascader(  {
        elem:`#userLevel`,
        clearable: true, // 显示清除按钮
        disabled:true,
        // options:data,
        props: {
            multiple: false, // 允许多选
            // strictMode:true//开启严格模式
        },
    })
    priceUserLevelCas.changeEvent(function (value){
        console.log('级别的变化',value)
    })
    let priceUserTypeCas=layui.layCascader({
        elem:`#userType`,
        clearable: true, // 显示清除按钮
        disabled:true,
        // options:data,
        props: {
            multiple: true, // 允许多选
            // strictMode:true//开启严格模式
        },
        // value:selectedData
    })
    priceUserTypeCas.changeEvent(function (value,node){
        console.log('类型的变化：',value,node)
    })
    let priceSpeUserCas=layui.layCascader({//单选
        elem:`#speUser`,
        disabled:true,
        clearable: true, // 显示清除按钮
        props: {
            multiple: true, // 允许多选
            // strictMode:true//开启严格模式
        },
    })
    priceSpeUserCas.changeEvent(function (value){
        console.log('用户变化',value,typeof value)
    })
    // 价格规则列表
    // let priceRuleList=[]
    // 规则类型数组(表格展示的时候把数字转成对应类型)
    const ruleType=['数据产品','算法服务产品','应用产品']

    //可见 表格实例
    const visibleRuleTable= table.render({
        elem: '#visiRuleTable'
        ,height:'.control'
        ,data:[]
        ,page: false //开启分页
        ,cols: [[ //表头
            {  title: '选择规则', width: "10%",templet:function (){
                    return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="select">选择</a>
                `
                }},
            { title: '序号', width:60,type:'numbers', }
            ,{field: 'systemControlName', title: '规则名', }
            // ,{field: 'isVisible', title: '可见性', width:'10%'}
            // ,{field: 'speUserList', title: '指定用户', width:'15%',templet: function (d){
            //         if (d.speUserList&&d.speUserList.length>0){
            //             const speUserNameList= d.speUserList.map(item=>item.speUserName).join(',')
            //             return `<span>${speUserNameList}</span>`
            //         }else {
            //             return  `<span>暂无</span>`
            //         }
            //     }}
            // ,{field: 'speUserTypeList', title: '用户类型', width: '15%',templet:function (d){
            //         if (userType&&userType.length>0&&d.speUserTypeList&&d.speUserTypeList.length){
            //             const speUserTypeNameList=d.speUserTypeList.map(item => userType[item]).join(',');
            //             return `<span>${speUserTypeNameList}</span>`
            //         }
            //         else {
            //             return  `<span>暂无</span>`
            //         }
            //     }
            // }
            // ,{field: 'userLevel', title: '用户级别', width: '15%',templet:function (d){
            //         if (userLevel&&userLevel.length>0&&d.userLevel){
            //             const userLevelName=userLevel[d.userLevel];
            //             return `<span>${userLevelName}</span>`
            //         }else {
            //             return  `<span>暂无</span>`
            //         }
            //     }}
            ,{field: 'remark', title: '备注',}
        ]]
    })
    table.on('tool(visiRuleTableFilter)',function (obj){
        const data=obj.data;
        if (obj.event==='select'){
            visibleFormValue(data)
            controlRuleId=data.id;
        }
    })
    // 价格表格实例
    const priceRuleTable= table.render({
        elem: '#priceRuleTable'
        ,height: '.layui-tab-item'
        ,data:[]
        ,cols: [[ //表头
            {  title: '选择规则', width:120,templet:function (){
                    return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="select">选择</a>
                `
                }},
            { title: '序号',type:"numbers", width:60}
            ,{field: 'systemBuyName', title: '规则名称', width:160}
            ,{field: 'systemBuyType', title: '规则类型', templet:
                    function (d){
                        return `<span>${ruleType[Number(d.systemBuyType)]}</span>`
                    }
            }
            ,{field: 'userRule', title: '用户条件'}
            ,{field: 'priceRule', title: '规则内容'}
            ,{field: 'remark', title: '备注', width: 200,}

        ]]
    })
    table.on('tool(priceRuleTableFilter)',function (obj){
        const data=obj.data;
        if (obj.event==='select'){
            
            formValue(data)
            buyRuleId=data.id;
        }
    })
    // 事件处理部分

    // 文件注册
    layui.use(['upload','form'], function() {

        //执行实例
        const uploadInst = upload.render({
            elem: '#uploadRootFile' //绑定元素
            , url: window.Http + '/datasourceBase/file' //上传接口
            ,headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                }
            ,accept:'file'
            // ,auto: false //选择文件后不自动上传
            , done: function (res) {
                //上传完毕回调
                if (res.code === 200) {
                    layer.msg('上传成功')
                } else {
                    layer.msg(res.msg)
                }

            }
        });
    })


    //上传图标文件
    // let IconUrl = "";
    const inputButton = document.querySelector("#iconButton")
    const inputFile = document.querySelector("#icon")
    inputButton.onclick = (event) => {
        inputFile.click();
    }
    inputFile.onchange = (event) => {
        const files = event.target.files;
        console.log(files);
        for (let i = 0; i < event.target.files.length; i++) {
            let file = event.target.files[i];
            uploadFile(file).then(res => {
                url = res.url;
                $("#dataSourceIconUrl").attr("src", url);
            });
        }
    };



    // 保存按钮
    $('#cancelAllForm').on('click',function (){
        // window.location.href='./mySpace.html'
        console.log('data', data)
        const formdata=form.val('BaseInfoForm')
        formdata.sourceNumber=Number(formdata.sourceNumber)
        // const controlRuleId=visibleRuleCas.getCheckedValues()
        // const buyRuleId=priceRuleCas.getCheckedValues()
        delete formdata.verifyCode;
        data=formdata;
        data.controlRuleId=controlRuleId;
        data.buyRuleId=buyRuleId
        data.iconUrl=url
        data.id=id;
        data.status=-1
        $.ajax({
       timeout:30000,
            url: window.Http + "/datasourceBase",
            type: 'POST',
            headers: {
                'Authorization': "Bearer " + sessionStorage.getItem('Token')
            },
            data:JSON.stringify(data),
            contentType:"application/json",
            success:function (res){
                if (res.code===200){
                    layer.msg('保存成功')
                    // setTimeout(function(){
                    //     window.location.href='../../mySpace.html'
                    // },1000)
                }else {
                    layer.msg(res.msg)
                }
            }
        })
    })
    // 功能函数部分

    // 数据转换成级联列表需要的样式
    // data:原始数组，value:绑定的值（id），label：标签显示值，返回正确格式数组
    function dataFormat(data,value,label){
        let arr=[]
        data.forEach(function (item,index){
            arr[index]={value:'',label:''}
            arr[index].value=data[index][value];
            arr[index].label=data[index][label]
        })
        return arr;
    }
    // 可见的表单赋值
    function visibleFormValue(data){
        let single=null;
        let collection=null
        console.log('data', data)
        if (!data){
            form.val('visibleNameForm',{
                "systemControlName":null,
                "visibleRuleRemark":null
            })
            form.val('visibleForm',{
                "mode":1,
                "userLevelMethod":0,
                "userLevelValue":0,
                "isVisible":0
            })
            visibleUserLevelCas.setValue(0)
            visibleUserTypeCas.setValue([]);
            visibleSpeUserCas.setValue([]);
        }else {
            single=JSON.parse(data.single);
            collection=JSON.parse(data.collection)
            form.val('visibleNameForm',{
                "systemControlName":data.systemControlName||null,
                "remark":data.remark||null
            })
            form.val('visibleForm',{
                "mode":data.ruleMode||1,
                "userLevelMethod":single[0].method||0,
                "userLevelValue":single[0].value||0,
                "isVisible":data.isVisible
            })
            // const userTypeSet = collection.find(item => item.class === 'userType').set;
            // const speUserSet = collection.find(item => item.class === 'speUser').set;
            const typeIds=data.speUserTypeList.map(item=>item.toString())
            visibleUserTypeCas.setValue(typeIds);
            visibleSpeUserCas.setOptions(dataFormat(data.speUserList,'speUserId','speUserName'))
            const speUserIds=data.speUserList.map(item=>item.value)
            visibleSpeUserCas.setValue(speUserIds);
            visibleUserLevelCas.setValue(single[0].value)
        }

    }

    // 申购相关表单赋值
    function formValue(data){
        console.log('data', data)
        let userRule=null;
        let priceRule=null;
        const resetForm={
            "minValue":null,
            "maxValue":null,
            "minPrice":null,
            "maxPrice":null,
            "calcway":"average",
        }
        if (!data){
            form.val('nameForm',{
                "systemBuyName":null,
                "systemBuyType":null,
                "remark":null
            })
            // 是否允许议价
            form.val('isDiscuss',{
                "isDiscuss":0
            })
            form.val('userForm',{
                "mode":1,
                "userLevelMethod":0,
                "userLevelValue":0,
                "isVisible":0,
                "searchUserName":null
            })
            priceUserLevelCas.setValue(0)
            priceUserTypeCas.setValue([])
            priceSpeUserCas.setValue([])
            // 价格相关表单赋值
            form.val('useDuring',{
                ...resetForm,
                "useDuringSelectway":0
            })
            form.val('useTimes',{
                ...resetForm,
                "useTimesSelectway":0
            })
            form.val('useSite', {
                ...resetForm,
                "useSiteSelectway":0
            })
            form.val('buyDuring',resetForm)
            form.val('buyTimes',resetForm)
            form.val('buyRecord',resetForm)
            form.val('securityForm',{
                "confirmSelect":0,
                "confirmPrice":null,
                "authSelect":0,
                "authPrice":null,
                "encodeSelect":0,
                "encodePrice":null,
                "codePlace":"platform",
                "encodeWay":"random"
            })
        }else {
            userRule=JSON.parse(data.userRule)
            console.log('form userRule',  userRule)
            priceRule=JSON.parse(data.priceRule)
            // 名字表单赋值
            form.val('nameForm',{
                "systemBuyName":data.systemBuyName,
                "systemBuyType":data.systemBuyType,
                "remark":data.remark
            })
            // 适应用户表单赋值
            form.val('userForm',convertToUserForm(userRule))
            // 价格相关表单赋值
            form.val('useDuring',{
                ... priceRule.use.during,
                'useDuringSelectway':priceRule.use.during.selectway
            })
            form.val('useTimes',{
                ...priceRule.use.times,
                'useTimesSelectway':priceRule.use.times.selectway
            })
            form.val('useSite',{
                ...priceRule.use.site,
                "useSiteSelectway":priceRule.use.site.selectway
            })
            form.val('buyDuring',priceRule.buy.during)
            form.val('buyTimes',priceRule.buy.times)
            form.val('buyRecord',priceRule.buy.record)
            form.val('securityForm',fillSecurityFormFromData(priceRule.security))
            // 是否允许议价
            form.val('isDiscuss',{
                "isDiscuss":priceRule.isDiscuss
            })
        }

    }
    // 把数据转成表单格式-适应用户
    function convertToUserForm(userRuleAttribute) {
        console.log('userRuleAttribute',userRuleAttribute)
        const userForm = {
            "isVisible": userRuleAttribute.isVisible,
            "mode": userRuleAttribute.mode,
            "userLevelMethod": userRuleAttribute.single.find(cond => cond.type === 'userLevel').method,
            "userLevelValue": userRuleAttribute.single.find(cond => cond.type === 'userLevel').value
        };
        const userLevelValue=userRuleAttribute.single.find(cond => cond.type === 'userLevel').value
        const userTypeSet = userRuleAttribute.collection.find(item => item.class === 'userType').set;
        const speUserSet = userRuleAttribute.collection.find(item => item.class === 'speUser').set;

        priceUserTypeCas.setValue(userTypeSet);
        // priceSpeUserCasRender(speUserSet,speUserSet.map(item=>item.value))
        priceSpeUserCas.setOptions(speUserSet)
        console.log('speUserSet', speUserSet)
        const speUserIds=speUserSet.map(item=>item.value)
        console.log('speUserIds', speUserIds)
        priceSpeUserCas.setValue(speUserIds)
        // priceSpeUserCas.setValue(speUserSet);
        priceUserLevelCas.setValue(userLevelValue)
        return userForm;
    }
    // 把数据转成对应表单格式
    function fillSecurityFormFromData(data) {
        return {
            "confirmSelect" : data.confirm.select,
            "confirmPrice" :data.confirm.price,
            "authSelect": data.auth.select,
            "authPrice" : data.auth.price,
            "encodeSelect" : data.encrypt.encode.select,
            "encodePrice" :data.encrypt.encode.price,
            "encodeWay" :data.encrypt.way.select,
            "codePlace" : data.encrypt.place.select,
        };
    }
    //上传图标
    function uploadFile(file) {
        const form = new FormData();
        form.append('file', file);
        return new Promise(function(resolve, reject) {
            $.ajax({
       timeout:30000,
                type: 'POST',
                url: window.Http + "/common/upload",
                headers: {
                    'Authorization': "Bearer " + sessionStorage.getItem('Token')
                },
                data: form,
                mimeType: "multipart/form-data",
                contentType: false,
                processData: false,
                dataType: "json",
                success: function (res) {
                    if (res.code === 200) {
                        resolve(res); // 成功时将响应传递给调用者
                    } else {
                        layer.msg(res.msg);
                        reject(new Error("请求失败")); // 失败时将错误传递给调用者
                    }

                },
                error: function (xhr, status, error) {
                    reject(new Error("请求出错：" + error)); // 失败时将错误传递给调用者
                }
            })
        })
    }
})

